function [TranMat,quan,transquan] = maketranmat(C,N)
% [TRANMAT, QUAN, TRANSQUAN] = MAKETRANMAT(C,N) makes the transition
% matrix(TRANMAT), the feature matrix(QUAN), and the sequence of
% quantizers(TRANSQUAN) based on the data from the cyberglove(C). N is the
% number of quantizers.
% written by Taro Kiritani
% email address: tarokiritani2008@u.northwestern.edu

F = (diff(C'))';
F = sum(abs(F));
figure;plot(F);
F(F > 50) = -1;
F(F~=-1) = 0;
ind = F +1;
% Compute the derivative of signal from each sensor. Then, divide the whole
% data into two phases (static and transition). Transition phase is defined
% as the point at which the sum of absolute values of derivatives is larger
% than 50.
C = C(:,2:length(C)) .* repmat(ind,size(C,1),1);
eraseind = sum(C);
eraseind(eraseind ~= 0) = 1;
eraseind = eraseind .* (1:length(eraseind));
eraseind = setdiff(eraseind,0);
C = C(:,eraseind);
% Extract static phases.
[quan,index] = TSVQ(C',N);
% quantizers of static phase data are computed. The number of quantizers is
% given by N.
nonzeroind = find(ind);
index1 = zeros(1,length(ind));
index1(nonzeroind) = index;

index = index1;
A = diff(ind).*(2:length(ind));
A = A(A~=0);
if A(1)<0
A(1)=[];
end
if mod(length(A),2)==1
A = A(1:length(A)-1);
end
A = reshape(A,2,[]);
A = abs(A);
B(1,:) = floor((2 * A(1,:) + A(2,:))/3);
B(2,:) = floor((A(1,:) + 2 * A(2,:))/3);
B = reshape(B,1,[]);
% pick up the points which divide a single static phase into three portions
% of equal length.
C = sum(A);
C = floor(C/2);
% pick up the points which divide a signle static phase into two parts of
% equal length. If want to pick up two points from a static phase, make the
% two lines comment.
B = C;
transquan = index(B);
quan = quan';
quan = quan(:,unique(transquan));
miss = setxor(index(B),[1:N]);
miss = sort(miss,'descend');
for i = 1:length(miss)
transquan(transquan > miss(i)) = transquan(transquan > miss(i)) - 1;
end
TranMat = Transition2(transquan,max(transquan));
% Make the transition matrix.

function [T] = transition2(ind,N)
% [T] = TRANSTION(IND,N) computes the transition matrix of ind (vector).
T = zeros(N,N);
for i = 1:length(ind)-1
T(ind(i),ind(i+1)) = T(ind(i),ind(i+1)) + 1;
end


